import {ApiData, MyComment, PageData} from "@/interfaces/apiResponse.ts";
import myAxios from "@/plugins/axios";
import {ElMessageBox} from "element-plus";

export default ()=>{
    const comments = ref<MyComment[]>();
    const pageAllComments = ref<PageData<MyComment>>();
    const getComments = async (t_id:any)=>{
        const res = await myAxios.request<ApiData<MyComment[]>>({
            url: `list/comment/${t_id}`
        });
        comments.value = res.data;
    }
    const getAllComments = async (page = 1, params = {})=>{
        //key=abc&keywords=bbb
        const paramsStr = Object.entries(params).map(e => e.join('=')).join('&');
        pageAllComments.value = await myAxios.request<PageData<MyComment>>({
            url: `get_all_comments?page=${page}&` + paramsStr
        });
    }
    const addComment = async (data:any)=>{
        const res = await myAxios.request<ApiData<MyComment>>({
            url:`comment/${data.t_id}`,
            method:'POST',
            data
        })
        comments.value?.push(res.data);
    }
    const addReply = async (data:any)=>{
        const res = await myAxios.request<ApiData<MyComment>>({
            url:`reply/comment/${data.t_id}/${data.c_id}`,
            method:'POST',
            data
        })
        return res.data;
    }
    const delComment = async (c_id:any)=>{
        try {
            await ElMessageBox.confirm(
                '您真的要删除该评论吗?',
                '删除提示',
                {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
            await myAxios.request<ApiData<null>>({
                url:`comment/${c_id}`,
                method:'DELETE',
            })
            location.reload();
        }catch (error){

        }
    }
    return {comments,getComments,addComment,addReply,delComment,pageAllComments,getAllComments}
}